<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="90px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="分公司名称" size="small">
            <el-input type="text" v-model="searchForm.companyName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="合作年限" size="small">
            <el-input type="number" v-model.number="searchForm.teamworkYear"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="支付阶段" size="small">
            <el-select v-model="searchForm.stage" placeholder="请选择">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="item in global.branchinformationStageList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col class="singleDatePicker">
          <el-form-item label="起始时间" size="small">
            <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              value-format="timestamp"
              placeholder="选择起始时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="singleDatePicker">
          <el-form-item label="终止时间" size="small">
            <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              value-format="timestamp"
              placeholder="选择终止时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
      @openVisible="openVisible"
    >
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="120">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.companyId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="450px">
      <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="120px">
        <el-form-item label="分公司名称" size="small">
          <el-input type="text" v-model="teamRow.companyName"></el-input>
        </el-form-item>
        <el-form-item label="地址" size="small">
          <el-input type="text" v-model="teamRow.address"></el-input>
        </el-form-item>
        <el-form-item label="规模" size="small">
          <el-input type="text" v-model="teamRow.scale"></el-input>
        </el-form-item>
        <el-form-item label="法人姓名" size="small">
          <el-input type="text" v-model="teamRow.personName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" size="small">
          <el-input type="text" v-model="teamRow.contact"></el-input>
        </el-form-item>
        <el-form-item label="行政联系电话" size="small">
          <el-input type="text" v-model="teamRow.administrativeContact"></el-input>
        </el-form-item>
        <el-form-item label="起始时间" size="small">
          <el-date-picker
            v-model="teamRow.startTime"
            type="date"
            value-format="timestamp"
            placeholder="选择起始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="终止时间" size="small">
          <el-date-picker
            v-model="teamRow.endTime"
            type="date"
            value-format="timestamp"
            placeholder="选择终止时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合作年限" size="small">
          <el-input type="number" v-model.number="teamRow.teamworkYear">
            <span slot="suffix">年</span>
          </el-input>
        </el-form-item>
        <el-form-item label="管理费" size="small">
          <el-input type="number" v-model.number="teamRow.managementFee">
            <span slot="suffix">万元</span>
          </el-input>
        </el-form-item>
        <el-form-item label="支付阶段" size="small">
          <el-select v-model="teamRow.stage" placeholder="请选择">
            <el-option
              v-for="item in global.branchinformationStageList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="营业执照图片" size="small">
          <input type="file" ref='businessPhoto' accept="image/*" @change="fileUpload($event,'businessPhotoFile')">
        </el-form-item>
        <el-form-item label="开户许可证图片" size="small">
          <input type="file" ref='openingPhoto' accept="image/*" @change="fileUpload($event,'openingPhotoFile')">
        </el-form-item>
        <el-form-item label="信用机构许可证" size="small">
          <input type="file" ref='institutionPhoto' accept="image/*"
                 @change="fileUpload($event,'institutionPhotoFile')">
        </el-form-item>
        <el-form-item label="备注说明" size="small">
          <el-input type="textarea" v-model="teamRow.remark"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
        <el-button size="small" @click="outerVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="imgMsg.label" :visible.sync="imgVisible" width="600px">
      <img class="img-dialog" :src="imgMsg.src" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import {
    getList,
    addOutCompany,
    selectOutCompany,
    delOutCompany,
    updateOutCompany
  } from '@/api/branchinformation'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const time = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const stage = function(row, column) {
    if (row.stage) {
      let obj = {}
      obj = global.branchinformationStageList.find((item) => {
        return item.value === row.stage // 筛选出匹配数据
      })
      return obj.label
    }
  }

  const filePath = {
    props: ['colConfig'],
    methods: {
      openVisible(label, src) {
        const msg = {
          label: label,
          src: src
        }
        this.$emit('openImgVisible', msg)
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
      <a v-if="scope.row[colConfig.prop]" @click="openVisible(colConfig.label,scope.row[colConfig.prop])">查看
      </a>
      <a v-else style="color: red">X</a>
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [

          { prop: 'companyName', label: '分公司名称', width: '150', fixed: true },
          { prop: 'address', label: '地址', width: '150' },
          { prop: 'scale', label: '规模', width: '150' },
          { prop: 'personName', label: '法人姓名', width: '150' },
          { prop: 'contact', label: '联系电话', width: '150' },
          { prop: 'administrativeContact', label: '行政联系电话', width: '150' },
          { prop: 'startTime', label: '起始时间', width: '150', component: time },
          { prop: 'endTime', label: '终止时间', width: '150', component: time },
          { prop: 'teamworkYear', label: '合作年限(年)', width: '150' },
          { prop: 'managementFee', label: '管理费(万元)', width: '150' },
          { prop: 'stage', label: '支付阶段', width: '150', formatter: stage },
          { prop: 'businessPhoto', label: '营业执照图片路径', width: '150', component: filePath },
          { prop: 'openingPhoto', label: '开户许可证图片路径', width: '150', component: filePath },
          { prop: 'institutionPhoto', label: '信用机构许可证图片路径', width: '160', component: filePath },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        propertyNoList: [],
        tenderNames: [],
        infoTitles: [],
        listLoading: true,
        dialogTitle: '新增分公司信息概况',
        dialogType: 0,
        teamRow: {
          stage: 1
        },
        teamRowClear: {
          stage: 1
        },
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        innerVisible: false,
        pca: pca,
        rules: {
          checkDate: [
            { required: true, message: '请选择盘点日期', trigger: 'change' }
          ],
          user: [
            { required: true, message: '请输入使用人', trigger: 'change' }
          ],
          officeTable: [
            { required: true, message: '请输入办公桌', trigger: 'change' }
          ],
          officeChair: [
            { required: true, message: '请输入办公椅', trigger: 'change' }
          ],
          computerBuy: [
            { required: true, message: '请输入电脑购买年份', trigger: 'change' }
          ]
        },
        visible: false,
        imgVisible: false,
        imgMsg: {}
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        console.log(this.searchFormList)
        getList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        this.outerVisible = true
        this.dialogTitle = '新增分公司信息概况'
        this.fileClear()
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.dialogType = 1
        this.teamRow.isTender = 1
      },
      editTeam(companyId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改分公司信息概况'
        this.dialogType = 0
        this.fileClear()
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          companyId: companyId
        }
        selectOutCompany(params).then(response => {
          const data = response.responseBody
          this.teamRow = Object.assign({}, this.teamRow, data)
        })
      },
      submitForm(formName) {
        const params = new FormData()
        params.append('companyName', this.teamRow.companyName || '')
        params.append('address', this.teamRow.address || '')
        params.append('scale', this.teamRow.scale || '')
        params.append('personName', this.teamRow.personName || '')
        params.append('contact', this.teamRow.contact || '')
        params.append('administrativeContact', this.teamRow.administrativeContact || '')
        if (this.teamRow.startTime) {
          params.append('startTime', this.teamRow.startTime)
        }
        if (this.teamRow.endTime) {
          params.append('endTime', this.teamRow.endTime)
        }
        params.append('teamworkYear', this.teamRow.teamworkYear || 0)
        params.append('managementFee', this.teamRow.managementFee || 0)
        params.append('stage', this.teamRow.stage)
        if (this.teamRow.businessPhotoFile) {
          params.append('businessPhotoFile', this.teamRow.businessPhotoFile)
        }
        if (this.teamRow.openingPhotoFile) {
          params.append('openingPhotoFile', this.teamRow.openingPhotoFile)
        }
        if (this.teamRow.institutionPhotoFile) {
          params.append('institutionPhotoFile', this.teamRow.institutionPhotoFile)
        }
        if (!this.dialogType) {
          params.append('companyId', this.teamRow.companyId)
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              addOutCompany(params).then(response => {
                this.outerVisible = false
                this.fetchData()
              })
            } else {
              updateOutCompany(params).then(response => {
                this.outerVisible = false
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          companyId: scope.row.companyId,
          isDel: 1
        }
        delOutCompany(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      openVisible(msg) {
        this.imgVisible = true
        this.imgMsg = msg
      },
      fileClear() {
        if (this.$refs.businessPhoto) {
          this.$refs.businessPhoto.value = ''
        }
        if (this.$refs.openingPhoto) {
          this.$refs.openingPhoto.value = ''
        }
        if (this.$refs.institutionPhoto) {
          this.$refs.institutionPhoto.value = ''
        }
      },
      fileUpload(event, teamRowName) {
        this.$set(this.teamRow, teamRowName, event.target.files[0])
      }
    },
    mounted() {
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
    .img-dialog {
      max-width: 540px;
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  a, a:focus, a:hover {
    color: #409EFF;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
